package com.example.demo.service.impl;

import com.example.demo.entity.Menu;
import com.example.demo.entity.Result;
import com.example.demo.mapper.MenuMapper;
import com.example.demo.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.SimpleFormatter;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public List<Menu> getMenu(Map<String, Object> params) {
        List<Menu> list=menuMapper.getMenu(params);
        return list;
    }

    @Override
    public Result getMenuInfo(Map<String, Object> params) {
        Integer pageIndex=Integer.parseInt(params.get("pageIndex").toString())-1;
        Integer pageSize=Integer.parseInt(params.get("pageSize").toString());
        params.put("pageIndex",pageIndex*pageSize);
        params.put("pageSize",pageSize);
        List<Map<String,Object>> result=menuMapper.getMenuInfo(params);
        int count=menuMapper.getMenuCont();
        return Result.ok(result).setRecordsCount((long) count);
    }

    @Transactional
    @Override
    public Result insertMenu(Map<String, Object> params) {
        int count=menuMapper.getMenuId();
        params.put("menuId",count);
        if(Objects.isNull(params.get("upperId"))){
            params.put("upperId",0);
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        params.put("crtDt",sdf.format(new Date()));
        menuMapper.insertMenu(params);
        return Result.ok("新增菜单成功");
    }

    @Transactional
    @Override
    public Result updateMenu(Map<String, Object> params) {
        menuMapper.updateMenu(params);
        return Result.ok("维护菜单成功");
    }

    @Transactional
    @Override
    public Result insertRoleMeun(Map<String, Object> params) {
        //删除
        menuMapper.deleteRoleMenu(params);
        //添加
        if(params.get("nodeCheck")!=null){
            List<String> list= (List<String>) params.get("nodeCheck");
            list=list.stream().distinct().collect(Collectors.toList());
            params.put("nodeCheck",list);
            if(list.size()>0){
                menuMapper.insertRoleMenu(params);
            }

        }
        return Result.ok("配置菜单成功");
    }

    @Override
    public Result getRoleMenuId(Map<String, Object> params) {
        List<Map<String, Object>> list=menuMapper.getRoleMenuId(params);
        return Result.ok(list);
    }
}
